package com.yunkeji.api.test;

import cn.hutool.extra.ssh.JschUtil;
import com.jcraft.jsch.*;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class SSHtest {
    public static void main(String[] args){
        Session root = JschUtil.getSession("1.92.125.235", 22, "root", "D:\\aidong.pem",null);


        String host = "1.92.125.235";
        String user = "root";
        String password = "password";
        String command = "df -h"; // 获取磁盘空闲状态

        try {
            JSch jsch = new JSch();
           // jsch.addIdentity("D:\\aidong.pem",null);
            Session session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);

            channelExec.setErrStream(System.err);
            InputStream in = channelExec.getInputStream();
            channelExec.connect();

            // 读取命令输出
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }
                if (channelExec.isClosed()) {
                    if (in.available() > 0) continue;
                    System.out.println("Exit status: " + channelExec.getExitStatus());
                    break;
                }
                Thread.sleep(100);
            }

            channelExec.disconnect();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
